/*
 * @lc app=leetcode.cn id=56 lang=javascript
 *
 * [56] 合并区间
 */

// @lc code=start
/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
var merge = function (intervals) {
    if(intervals.length<=1) return intervals;
    intervals.sort((a,b)=>a[0]-b[0])
    let tar = [],cache = intervals[0];
    for(let i = 1; i < intervals.length; i ++){
        if(intervals[i][0]<=cache[1]){
            if(intervals[i][1]>cache[1]){
                cache[1] = intervals[i][1]
            }
            if(i===intervals.length-1) tar.push(cache)
        }else{
            tar.push(cache)
            cache = intervals[i];
            if(i===intervals.length-1) tar.push(cache)
        }
    }
    return tar
};
// @lc code=end